<template>
  <div class="login">
    <div class="decr">
      <div class="imgP">
        <img src="../../assets/好大一只.png" alt="Logo" />
      </div>
      <div class="content">
        <h1>Hi~</h1>
        <section>
          这是一个初创公司，在这个公司里，我们希望通过自己的努力，帮助更多的人。
        </section>
      </div>
    </div>
    <div class="login-box">
      <h3>欢迎登录!</h3>
      <form @submit.prevent="login">
        <div class="input-box" v-if="!usePhoneLogin">
          <label for="email">邮&emsp;箱：</label>
          <input
            type="email"
            name="email"
            id="email"
            v-model="formParam.email"
            placeholder="请输入邮箱~"
          />
        </div>
        <div class="input-box" v-if="usePhoneLogin">
          <label for="phone">手机号：</label>
          <input
            type="tel"
            maxlength="11"
            name="phone"
            id="phone"
            v-model="formParam.cellphone"
            placeholder="请输入手机号~"
          />
        </div>
        <div class="input-box" v-if="useCodeLogin">
          <label for="code">验证码：</label>
          <div class="code_box">
            <input
              type="text"
              id="code"
              v-model="formParam.code"
              maxlength="6"
              placeholder="请输入6位验证码~"
            />
            <el-button
              type="button"
              class="code-button"
              :disabled="isButtonDisabled"
              @click="sendCode"
            >
              {{ countdown > 0 ? countdown + "秒后重发" : "发送验证码" }}
            </el-button>
          </div>
        </div>
        <div class="input-box" v-if="!useCodeLogin">
          <label for="password">密&emsp;码：</label>
          <input
            type="password"
            v-model="formParam.password"
            id="password"
            placeholder="请输入登录密码~"
          />
        </div>
        <div class="tooltips">
          <div @click="toggleEmailLogin">
            {{ usePhoneLogin ? "使用邮箱登录" : "使用手机登录" }}
          </div>
          <div @click="toggelCodeLogin">
            {{ useCodeLogin ? "使用密码登录" : "使用验证码登录" }}
          </div>
        </div>
      </form>
      <div class="infobox">
        <el-checkbox v-model="userDeal" @change="toggleCheck">
          <span>用户登录协议</span>
          <el-dialog title="用户登录协议" :visible="userDeal"></el-dialog>
        </el-checkbox>

        <router-link class="link" to="/forgot">忘记密码</router-link>
        <router-link class="link" to="/register">前往注册</router-link>
      </div>
      <button type="submit" class="login-button" @click="login">登录</button>
    </div>
  </div>
  <footer class="footer">
    <a href="https://beian.miit.gov.cn/" target="_blank">
      备案号: 蜀ICP备2024086875号-1
    </a>
    <div>
      <a
        href="https://www.douyin.com/user/MS4wLjABAAAAJxUIX2GMq0-rcucksrrllJj93HHnceibxk40_PWmeX0"
        target="_blank"
        >© 好大一只</a
      >
    </div>
  </footer>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted, onMounted } from "vue";
import { useLoginStore, useUserStore } from "../../store";
import { LoginParams, SendEmailCodeParams } from "../../types/user";

import { sendEmailCode } from "../../api/auth";

import { ElMessage } from "element-plus";
import router from "../../router";

let store = useLoginStore();
let useCodeLogin = ref(false);
let usePhoneLogin = ref(false);
let formParam = ref<LoginParams>({
  email: "",
  code: "",
  password: "",
  mode: "",
  cellphone: "",
});
let userDeal = ref(false);

const countdown = ref(0);
const isButtonDisabled = ref(false);
let countdownInterval: string | number | NodeJS.Timeout | undefined;

const updateCountdown = () => {
  if (countdown.value > 0) {
    countdown.value -= 1;
    localStorage.setItem("countdown", countdown.value.toString());
  } else {
    isButtonDisabled.value = false;
    localStorage.removeItem("countdown");
    localStorage.removeItem("codeExpiryTime"); // 清除过期时间
    clearInterval(countdownInterval);
  }
};
function toggleCheck(value: boolean) {
  if (value) {
    console.log("用户已阅读并同意用户注册协议");
  } else {
    console.log("用户取消了对用户注册协议的同意");
  }
}

function toggleEmailLogin() {
  usePhoneLogin.value = !usePhoneLogin.value;
}

function toggelCodeLogin() {
  useCodeLogin.value = !useCodeLogin.value;
  var localCount = localStorage.getItem("countdown");
  var savedCountdown = 0;
  if (localCount != null) {
    savedCountdown = parseInt(localCount) || 60;
  } else {
    localStorage.setItem("countdown", "0");
    savedCountdown = 0;
  }
  countdown.value = savedCountdown;
}
// 倒计时
const sendCode = async () => {
  // 校验手机号或邮箱是否为空
  if (formParam.value.cellphone === "" && formParam.value.email === "") {
    ElMessage.error("手机号或邮箱不能为空");
    return;
  }

  try {
    // 发送验证码的请求
    let sendEamilCodeParams: SendEmailCodeParams = {
      email: formParam.value.email,
      cellPhone: formParam.value.cellphone,
      mode: "login",
    };
    const response = await sendEmailCode(sendEamilCodeParams);

    if (response.code !== 200) {
      ElMessage.error(response.message);
      return;
    }

    ElMessage.success("发送成功");

    // 启动倒计时
    countdown.value = 60; // 设置倒计时时间为60秒
    isButtonDisabled.value = true;

    // 存储过期时间
    const codeExpiryTime = Date.now() + countdown.value * 1000;
    localStorage.setItem("countdown", countdown.value.toString());
    localStorage.setItem("codeExpiryTime", codeExpiryTime.toString());

    // 清除之前的倒计时
    clearInterval(countdownInterval);
    countdownInterval = setInterval(updateCountdown, 1000);
  } catch (error) {
    ElMessage.error("发送失败");
    // 不启动倒计时
    countdown.value = 0;
    isButtonDisabled.value = false;
  }
};

onUnmounted(() => {
  clearInterval(countdownInterval);
});
// 页面加载时初始化倒计时
onMounted(() => {
  const savedCountdown = parseInt(localStorage.getItem("countdown") || "0", 10);
  const codeExpiryTime = parseInt(
    localStorage.getItem("codeExpiryTime") || "0",
    10
  );
  const now = Date.now();

  // 如果倒计时未过期
  if (savedCountdown > 0 && now < codeExpiryTime) {
    countdown.value = Math.ceil((codeExpiryTime - now) / 1000); // 计算剩余秒数
    isButtonDisabled.value = true;
    countdownInterval = setInterval(updateCountdown, 1000);
  } else {
    // 重置倒计时数据
    localStorage.removeItem("countdown");
    localStorage.removeItem("codeExpiryTime");
  }
});
watch(countdown, (newVal) => {
  if (newVal <= 0) {
    isButtonDisabled.value = false;
  }
});

async function login() {
  if (useCodeLogin.value && usePhoneLogin.value) {
    formParam.value.mode = "phonemodecode";
  } else if (useCodeLogin.value && !usePhoneLogin.value) {
    formParam.value.mode = "emodecode";
  } else if (!useCodeLogin.value && usePhoneLogin.value) {
    formParam.value.mode = "phonemode";
  } else {
    formParam.value.mode = "emode";
  }
  try {
    const result = await store.login(formParam.value);
    sessionStorage.setItem("token", result!.token);
    ElMessage.success("请求成功");
    // window跳转到首页
    router.push("/");
  } catch (error) {
    ElMessage.error(String(error));
  }
}
</script>

<style lang="scss" scoped>
.login {
  // min-height: 100%;
  height: 100%;
  width: 100%;
  background: linear-gradient(to right, #a7e4f1 20%, #81cfe0 50%, #0083b0 80%);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .decr {
    height: 100%;
    width: 60%;
    background-color: antiquewhite;
    opacity: 0.8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px;

    .imgP {
      img {
        width: 100%;
        max-width: 300px;
        margin-bottom: 20px;
      }
    }

    .content {
      text-align: center;

      h1 {
        font-size: 2.5rem;
        color: #333;
        margin-bottom: 10px;
      }

      section {
        font-size: 1.25rem;
        color: #0083b0;
      }
    }
  }

  .login-box {
    flex: 1;
    max-width: 400px;
    padding: 20px;
    background-color: #f9f9f9;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    margin: 50px auto;
    text-align: left;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 50%;

    h3 {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
      font-size: 1.5rem;
    }

    form {
      position: relative;
      .input-box {
        margin-bottom: 15px;
        display: flex;
        align-items: center;

        label {
          flex: 0 0 80px; /* 控制 label 的固定宽度 */
          margin-right: 10px;
          color: #555;
        }

        input {
          flex: 1;
          padding: 10px;
          border: 1px solid #ddd;
          border-radius: 4px;
          outline: none;

          &:focus {
            border-color: #66afe9;
            box-shadow: 0 0 8px rgba(102, 175, 233, 0.6);
          }
        }
        .code_box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          #code {
            width: 30%;
            margin-right: 10px;
          }
          .code-button {
            height: 100%;
            background-color: #409eff;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;

            &:hover {
              background-color: #66b1ff;
            }

            &:disabled {
              background-color: #ddd;
              cursor: not-allowed;
            }
          }
        }
      }
      .tooltips {
        position: absolute;
        right: 0;
        bottom: 0;
        font-size: 10px;
        color: #999;
        div {
          display: inline-block;
          margin-right: 10px;
        }
        div:hover {
          cursor: pointer;
          color: #0083b0;
        }
      }
    }

    .infobox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .el-checkbox {
        flex-shrink: 0;
      }

      .link {
        color: #409eff;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #66b1ff;
        }
      }
    }

    .login-button {
      width: 100%;
      padding: 10px;
      background-color: #409eff;
      border: none;
      border-radius: 4px;
      color: white;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background-color: #66b1ff;
      }
    }
  }

  @media (max-width: 768px) {
    flex-direction: column;
    height: 100%;
    .decr {
      display: none; // 小屏幕时隐藏描述部分
    }

    .login-box {
      width: 90%;
      margin: 20px auto;
      padding: 20px;
    }
  }
}
</style>
